﻿using UnityEngine;
using System.Collections.Generic;

public class AudioManager : MonoBehaviour
{
    public static AudioManager Instance { get; private set; }

    [System.Serializable]
    public class Sound
    {
        public string name;
        public AudioClip clip;
        [Range(0f, 1f)] public float volume = 1f;
        [Range(0.1f, 3f)] public float pitch = 1f;
        public bool loop = false;
        [HideInInspector] public AudioSource source;
    }

    public List<Sound> sounds;
    public bool isisOpenSound = true;
    void Awake()
    {
        // 单例模式
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        // 为每个声音创建AudioSource组件
        foreach (Sound s in sounds)
        {
            s.source = gameObject.AddComponent<AudioSource>();
            s.source.clip = s.clip;
            s.source.volume = s.volume;
            s.source.pitch = s.pitch;
            s.source.loop = s.loop;
        }
    }



    /// <summary>
    /// 点击是否关闭音乐
    /// </summary>
    public void isOpenSound()
    {
        isisOpenSound = !isisOpenSound;
        if(isisOpenSound)
        {
            OpenAll();
        }
        else
        {
            closeAll();
        }

    }
    /// <summary>
    /// 关闭全部
    /// </summary>
    public void closeAll()
    {
        Debug.Log("声音关闭");
        foreach (Sound sound in sounds)
        {
            if (sound.source != null)
            {
                sound.source.mute = true; // 直接静音
              
            }
        }
    }

    // 打开所有声音（恢复原始音量）
    public void OpenAll()
    {
        Debug.Log("声音打开");
        foreach (Sound sound in sounds)
        {
            if (sound.source != null)
            {
                sound.source.mute = false; // 取消静音
            }
        }
    }

    // 播放声音
    public void Play(string name)
    {
        Sound s = sounds.Find(sound => sound.name == name);
        if (s == null)
        {
            Debug.LogWarning("Sound: " + name + " not found!");
            return;
        }
        s.source.Play();
    }

    // 停止声音
    public void Stop(string name)
    {
        Sound s = sounds.Find(sound => sound.name == name);
        if (s == null)
        {
            Debug.LogWarning("Sound: " + name + " not found!");
            return;
        }
        s.source.Stop();
    }

    // 暂停声音
    public void Pause(string name)
    {
        Sound s = sounds.Find(sound => sound.name == name);
        if (s == null)
        {
            Debug.LogWarning("Sound: " + name + " not found!");
            return;
        }
        s.source.Pause();
    }

    // 设置全局音量
    public void SetMasterVolume(float volume)
    {
        foreach (Sound s in sounds)
        {
            s.source.volume = s.volume * volume;
        }
    }
}